<?php
/**
 * @author HX<titanrain@163.com>
 */
class UserBookAR extends CActiveRecord{
	public static function model($className=__CLASS__){
		return parent::model($className);
	}

	public static function tblName()	{
		return 'ccs8_user_book';
	}
	
	public function tableName()	{
		return self::tblName();
	}
	
	public static function isExists($userId = 0,$bookId = 0){
		$cnt = DBUtil::count(self::tblName(),"fk_user=$userId and fk_book=$bookId");
		return $cnt > 0;
	}
	
	public static function queryById($bookId = 0,$userId = 0){
		$sql = 'select book_name,fk_category ';
		$sql .= DBUtil::buildFromSingleTbl(self::tblName());
		$sql .= 'where fk_book='.$bookId.' and fk_user='.$userId.' limit 1';
		return DBUtil::queryRow($sql);
	}
	
	public static function del($bookId = 0,$userId = 0){
		if($bookId == 0 || $userId == 0){
			return;
		}
		$sql = 'delete from '.self::tblName().' where fk_book='.$bookId.' and fk_user='.$userId.' limit 1';
		DBUtil::exec($sql);
	}
	
	public static function persist($userId,$bookId,$bookNameByUser,$categoryId){
		if(self::isExists($userId,$bookId)){
			return false;
		}
		self::saveUserBook($userId,$bookId,$bookNameByUser,$categoryId);
        return true;
	}
	
	public static function saveUserBook($userId,$bookId,$bookNameByUser,$categoryId){
		$props = array('fk_user'=>$userId,'fk_book'=>$bookId,'ctime'=>time(),'book_name'=>$bookNameByUser,'fk_category'=>$categoryId);
		DBUtil::insert(self::tblName(),$props);
	}
	
	public static function listBooks($cid = 0, $pageno = 1, $userId = 0){
		$condition = "fk_user=$userId";
		if($cid != 0){
			$condition .= " and fk_category=$cid";
		}
		
		$sql = 'select count(*) ';
		$sql .= DBUtil::buildFromSingleTbl(self::tblName());
		$sql .= 'where '.$condition.' limit 1';
		$cnt = DBUtil::queryScalar($sql);
		
		$page = new Page($pageno,Yii::app()->params['userHomePageSize']);
		$page->totalrecord = $cnt;
		
		$sql = 'select fk_book,book_name,ctime';
        $sql .= DBUtil::buildFromSingleTbl(self::tblName());
        $sql .= 'where '.$condition.' order by user_book_id desc';
        $sql .= $page->LimitStr();
        $recordlist = DBUtil::queryAll($sql);
        
        $size = count($recordlist);
        $bookIds = array();
        for($i=0;$i<$size;$i++){
        	$bookIds[] = $recordlist[$i]['fk_book'];
        }
        
        $details = BookAR::batchGetBookInfoByIds($bookIds);	
        
        for($i=0;$i<$size;$i++){
        	$recordlist[$i]['author'] = $details[$recordlist[$i]['fk_book']]['author'];
        	$recordlist[$i]['comment_times'] = $details[$recordlist[$i]['fk_book']]['comment_times'];
        }
        $page->recordlist = $recordlist;
        return $page;
	}
	    
    public static function userUserdCategoryIds($userId){
    	$sql = 'select fk_category ';
    	$sql .= DBUtil::buildFromSingleTbl(self::tblName());
    	$sql .= "where fk_user=$userId";
    	$cids = DBUtil::queryColumn($sql);
    	return array_unique($cids);
    }
}
